package org.base.baseproject.controller;

import org.base.baseproject.common.BaseResponse;
import org.base.baseproject.common.BusinessException;
import org.base.baseproject.common.ResultUtils;
import org.base.baseproject.domain.User;
import org.base.baseproject.service.RolePermissionService;
import org.base.baseproject.service.UserService;
import org.base.baseproject.utils.UserInfoUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RolePermissionService rolePermissionService;
    /**
     * 注册
     * @param user
     * @return
     */
    @PostMapping("register")
    public BaseResponse reg(@RequestBody User user) throws BusinessException {
        try {
            userService.reg(user);
        }catch (DataAccessException e){
            if (e.getCause() instanceof SQLIntegrityConstraintViolationException){
                if (e.getMessage().contains(" for key 'user.email'")) {
                    throw new BusinessException("邮箱已存在");
                }
                if (e.getMessage().contains(" for key 'user.userName'")){
                    throw new BusinessException("用户名已存在");
                }
            }
            throw new BusinessException("未知错误");
        }

        return ResultUtils.success(user);
    }

    /**
     * 登录
     * @param user
     * @return
     * @throws BusinessException
     */
    @PostMapping("login")
    public BaseResponse login(@RequestBody User user) throws BusinessException {
        return ResultUtils.success(userService.login(user));
    }
    @PreAuthorize("hasAuthority('admin')")
    @GetMapping("test")
    public BaseResponse loginTest(){
        List<String> rolePermissionByUserPid = rolePermissionService.getRolePermissionByUserPid(UserInfoUtils.getUserId());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return ResultUtils.success(rolePermissionByUserPid);
    }
    @GetMapping("getUserPermission")
    public BaseResponse getUserInfo(){
       return ResultUtils.success(rolePermissionService.getRolePermissionByUserPid(UserInfoUtils.getUserId()));
    }
}
